#include <fstream>
#include "headfiles.h"

using namespace std;

int main(int argc, char **argv) {
    if (argc != 3) {
        cout << "Usage: " << argv[0] << " in_file string" << endl;
        return 0;
    }

    string file_name(argv[1]);
    char *searched_str;
    if (strcmp(argv[2], "NULL") == 0) {
        searched_str = NULL;
    }
    else {
        string tmp_str(argv[2]);
        size_t tmp_size = tmp_str.size();
        searched_str = (char *)malloc(sizeof(char) * (tmp_size + 1));
        searched_str[tmp_size] = '\0';
        memcpy(searched_str, tmp_str.c_str(), tmp_size);
    }

    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return 1;
    }

    string str;
    if (getline(fs, str) == 0) {
        cout << "Read line false!" << endl;
        return 1;
    }
    int str_num = atoi(str.c_str());
    if (str_num <= 0) {
        cout << "String num " << str_num << " is invalid!" << endl;
        return 1;
    }

    char **str_array;
    str_array = (char **)malloc(sizeof(char *) * str_num);
    if (str_array == NULL) {
        cout << "Allocate string array error, NULL!" << endl;
        return 1;
    }

    int loc = 0;
    while (getline(fs, str)) {
        if (str.empty()) {
            str_array[loc] = NULL;
        }
        else {
            size_t str_size = str.size();
            str_array[loc] = (char *)malloc(sizeof(char) * (str_size + 1));
            if (str_array[loc] == NULL) {
                cout << "Allocate string " << loc << " buffer error, NULL!" << endl;
                return 1;
            }
            str_array[loc][str_size] = '\0';
            memcpy(str_array[loc], str.c_str(), str_size);
        }
        ++loc;
    }
    fs.close();

    sortStrings(str_array, str_num);
    for (int i = 0; i < str_num; i++) {
        cout << str_array[i] << endl;
    }
    cout << endl;

    int index;
    index = findString(str_array, str_num, searched_str);
    if (index == -1) {
        cout << "String " << argv[2] << " is not found!" << endl;
    }
    else {
        cout << "Index of string " << argv[2] << " is " << index << "." << endl;
    }

    free(searched_str);
    for (int i = 0; i < str_num; i++) {
        free(str_array[i]);
    }
    free(str_array);

    return 0;
}



